#include "communication-device-fingerprint.h"

CommunicationDeviceFingerPrint::CommunicationDeviceFingerPrint(FingerprintManager *fingerPrintManager) : fingerPrintManager(fingerPrintManager)
{
    handle["add"] = &CommunicationDeviceFingerPrint::add;
    handle["remove"] = &CommunicationDeviceFingerPrint::remove;
    handle["clear"] = &CommunicationDeviceFingerPrint::clear;
}

void CommunicationDeviceFingerPrint::communication(SmartDeviceNetProtocol &netprotocol, NetCommunication *netobj)
{
    string command = netprotocol.getCommand();
    auto func = handle[command];
    if (!func)
    {
        return;
    }
    (this->*func)(netprotocol, netobj);
}

void CommunicationDeviceFingerPrint::clear(SmartDeviceNetProtocol &netprotocol,
                                           NetCommunication *netobj)
{
    string command = netprotocol.getCommand();
    bool ok = fingerPrintManager->clearFingerPrintlib();
    string errmsg = ok ? "" : "error";
    replay(netobj, command, errmsg);

    return;
}

void CommunicationDeviceFingerPrint::add(SmartDeviceNetProtocol &netprotocol, NetCommunication *netobj)
{
    uint32_t userid = netprotocol.getUserID();
    string command = netprotocol.getCommand();

    bool ok = fingerPrintManager->recordFingerPrint(userid);

    string errmsg = ok ? "" : "error";
    replay(netobj, command, errmsg);
    return;
}

void CommunicationDeviceFingerPrint::remove(SmartDeviceNetProtocol &netprotocol, NetCommunication *netobj)
{
    string command = netprotocol.getCommand();
    uint32_t userid = netprotocol.getUserID();

    bool ok = fingerPrintManager->deleteFingerPrint(userid);
    string errmsg = ok ? "" : "error";
    replay(netobj, command, errmsg);

    return;
}

void CommunicationDeviceFingerPrint::replay(NetCommunication *netobj,
                                            const string &command,
                                            const string &errmsg,
                                            const string &data)
{

    SmartDeviceNetProtocol netProtocol;
    netProtocol.addCommand("fingerprint");
    netProtocol.addCommand(command);
    netProtocol.addResult(errmsg, data);

    string replyJsonData = netProtocol.toString();
    cout << "打印回复的json字符串" << replyJsonData << endl;
    // string 转  vector
    vector<uint8_t> packet;
    packet.assign(replyJsonData.begin(), replyJsonData.end());
    bool ret = netobj->sendPacket(packet);
    if (ret != true)
    {
        fprintf(stderr, "Fail to sendPacket \n");
        return;
    }

    return;
}
